<template>
    <div>
        <!-- 搜索栏 -->
        <div class="card" style="margin-bottom: 5px">
            <el-input style="width: 240px; margin-right: 10px" v-model="data.status" placeholder="请输入状态查询（如：RESERVED）"
                prefix-icon="Search"></el-input>
            <el-button type="primary" @click="load">查 询</el-button>
            <el-button type="warning" @click="reset">重 置</el-button>
        </div>

        <!-- 操作按钮 -->
        <div class="card" style="margin-bottom: 5px">
            <el-button type="primary" @click="handleAdd">新 增 预 订</el-button>
            <el-button type="danger" @click="delBatch">批 量 删 除</el-button>
            <el-button type="info" @click="toggleAutoRefresh">自动刷新</el-button>
        </div>

        <!-- 数据表格 -->
        <div class="card" style="margin-bottom: 5px">
            <el-table :data="data.tableData" stripe @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="预订ID" prop="id" />
                <el-table-column label="用户名称" prop="userName" />
                <el-table-column label="酒店名称" prop="hotelName" />
                <el-table-column label="房间名称" prop="roomType" />
                <el-table-column label="预订时间" prop="bookingDate" />
                <el-table-column label="入住时间" prop="checkInDate" />
                <el-table-column label="退房时间" prop="checkOutDate" />
                <el-table-column label="状态" prop="status" />
                <el-table-column label="总价（元）" prop="totalPrice" />
                <el-table-column label="操作" width="120">
                    <template #default="scope">
                        <el-button @click="handleUpdate(scope.row)" type="primary" :icon="Edit" circle></el-button>
                        <el-button @click="del(scope.row.id)" type="danger" :icon="Delete" circle></el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div style="margin-top: 15px">
                <el-pagination @size-change="load" @current-change="load" v-model:current-page="data.pageNum"
                    v-model:page-size="data.pageSize" :page-sizes="[5, 10, 15, 20]" background
                    layout="total, sizes, prev, pager, next, jumper" :total="data.total" />
            </div>
        </div>

        <!-- 新增/编辑对话框 -->
        <el-dialog title="预订信息" v-model="data.formVisible" width="600px" destroy-on-close>
            <el-form ref="formRef" :model="data.form" :rules="data.rules" label-width="100px"
                style="padding: 20px 40px 0 0">
                <!-- 用户ID -->
                <el-form-item label="用户ID" prop="userId">
                    <el-input v-model="data.form.userId" autocomplete="off" placeholder="请输入用户ID" />
                </el-form-item>

                <!-- 酒店ID -->
                <el-form-item label="酒店ID" prop="hotelId">
                    <el-input v-model="data.form.hotelId" autocomplete="off" placeholder="请输入酒店ID" />
                </el-form-item>

                <!-- 房间ID -->
                <el-form-item label="房间ID" prop="roomId">
                    <el-select v-model="data.form.roomId" placeholder="请选择房间" filterable>
                        <el-option
                            v-for="room in data.availableRooms"
                            :key="room.id"
                            :label="`${room.roomType} (¥${room.price}/晚)`"
                            :value="room.id"
                        />
                    </el-select>
                </el-form-item>

                <!-- 入住时间 -->
                <el-form-item label="入住时间" prop="checkInDate">
                    <el-date-picker v-model="data.form.checkInDate" type="date" format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd" placeholder="选择入住日期" />
                </el-form-item>

                <!-- 退房时间 -->
                <el-form-item label="退房时间" prop="checkOutDate">
                    <el-date-picker v-model="data.form.checkOutDate" type="date" format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd" placeholder="选择退房日期" />
                </el-form-item>

                <!-- 状态 -->
                <el-form-item label="状态" prop="status">
                    <el-select v-model="data.form.status" placeholder="请选择状态">
                        <el-option label="已预订" value="RESERVED" />
                        <el-option label="已取消" value="CANCELED" />
                        <el-option label="已完成" value="COMPLETED" />
                    </el-select>
                </el-form-item>

                <!-- 总价 -->
                <el-form-item label="总价（元）" prop="totalPrice">
                    <el-input-number v-model="data.form.totalPrice" :min="0" placeholder="请输入总价" />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="data.formVisible = false">取 消</el-button>
                    <el-button type="primary" @click="save">保 存</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { reactive, ref, watch, onMounted, onUnmounted } from "vue";
import { Edit, Delete, Search } from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";

// 初始化响应式数据
const data = reactive({
    status: null,          // 搜索条件：预订状态
    tableData: [],         // 表格数据
    pageNum: 1,            // 当前页码
    pageSize: 10,          // 每页数量
    total: 0,              // 总记录数
    formVisible: false,    // 对话框可见性
    form: {},              // 表单数据（新增/编辑）
    ids: [],               // 选中的预订ID列表
    rules: {               // 表单校验规则
        userId: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
        hotelId: [{ required: true, message: '请输入酒店ID', trigger: 'blur' }],
        roomId: [{ required: true, message: '请输入房间ID', trigger: 'blur' }],
        checkInDate: [{ required: true, message: '请选择入住时间', trigger: 'change' }],
        checkOutDate: [{ required: true, message: '请选择退房时间', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        totalPrice: [{ required: true, message: '请输入总价', trigger: 'blur' }]
    },
    availableRooms: []  // 可用房间列表
});

const formRef = ref();  // 表单引用

// 添加自动刷新定时器
const refreshTimer = ref(null);
const autoRefreshEnabled = ref(true);

// 添加检查最新预订的方法
const checkLatestBooking = async () => {
  if (!autoRefreshEnabled.value) return;
  
  try {
    const res = await request.get('/notification/latest-booking');
    if (res.code === '200' && res.data) {
      const latestBooking = res.data;
      
      // 检查是否为新预订（不在当前表格中）
      const isNew = !data.tableData.some(booking => booking.id === latestBooking.id);
      
      if (isNew) {
        ElMessage({
          message: `收到新预订: 用户${latestBooking.userName || latestBooking.userId}预订了${latestBooking.hotelName || '酒店'}`,
          type: 'success',
          duration: 5000
        });
        
        // 自动刷新数据
        load();
      }
    }
  } catch (error) {
    console.error('检查最新预订失败', error);
  }
};

// 修改startAutoRefresh方法，加入预订检查
const startAutoRefresh = () => {
  // 清除可能存在的定时器
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value);
  }
  
  if (autoRefreshEnabled.value) {
    // 设置新的定时器，每15秒检查一次最新预订
    refreshTimer.value = setInterval(() => {
      checkLatestBooking();
    }, 15000); // 15秒
  }
};

// 清除定时器
const stopAutoRefresh = () => {
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value);
    refreshTimer.value = null;
  }
};

// 切换自动刷新
const toggleAutoRefresh = () => {
  autoRefreshEnabled.value = !autoRefreshEnabled.value;
  if (autoRefreshEnabled.value) {
    ElMessage.success('自动刷新已开启');
    startAutoRefresh();
  } else {
    ElMessage.info('自动刷新已关闭');
    stopAutoRefresh();
  }
};

// 加载分页数据（调用后端 /booking/selectPage 接口）
const load = () => {
    request.get('/booking/selectPage', {
        params: {
            pageNum: data.pageNum,
            pageSize: data.pageSize,
            status: data.status  // 传递搜索条件到后端
        }
    }).then(res => {
        data.tableData = res.data.list;  // 表格数据
        data.total = res.data.total;     // 总记录数
    });
};

// 获取房间价格（使用房价制定服务）
const calculateRoomPrice = (roomId, checkInDate, checkOutDate) => {
    if (!roomId || !checkInDate || !checkOutDate) {
        return Promise.resolve(0);
    }
    
    return request.get(`/pricing/dateRangePrices/${roomId}`, {
        params: { startDate: checkInDate, endDate: checkOutDate }
    }).then(res => {
        if (res.code === '200') {
            // 计算日期范围内的总价
            let totalPrice = 0;
            const priceMap = res.data;
            for (const date in priceMap) {
                totalPrice += priceMap[date];
            }
            return totalPrice;
        } else {
            ElMessage.error(res.msg || '价格计算失败');
            return 0;
        }
    }).catch(() => {
        return 0;
    });
};

// 获取可用房间列表
const loadAvailableRooms = (hotelId, checkInDate, checkOutDate) => {
    if (!hotelId || !checkInDate || !checkOutDate) {
        return Promise.resolve([]);
    }
    
    return request.get('/roomAllocation/availableRooms', {
        params: { hotelId, checkInDate, checkOutDate }
    }).then(res => {
        if (res.code === '200') {
            return res.data;
        } else {
            ElMessage.error(res.msg || '获取可用房间失败');
            return [];
        }
    }).catch(() => {
        return [];
    });
};

// 监听房间ID、入住日期和退房日期变化，自动计算价格
watch([
    () => data.form.roomId,
    () => data.form.checkInDate,
    () => data.form.checkOutDate
], async ([roomId, checkInDate, checkOutDate]) => {
    if (roomId && checkInDate && checkOutDate) {
        const totalPrice = await calculateRoomPrice(roomId, checkInDate, checkOutDate);
        data.form.totalPrice = totalPrice;
    }
});

// 监听酒店ID变化，加载可用房间
watch(() => data.form.hotelId, async (hotelId) => {
    if (hotelId && data.form.checkInDate && data.form.checkOutDate) {
        const rooms = await loadAvailableRooms(hotelId, data.form.checkInDate, data.form.checkOutDate);
        data.availableRooms = rooms;
    }
});

// 重置搜索条件
const reset = () => {
    data.status = null;
    load();
};

// 打开新增对话框
const handleAdd = () => {
    data.formVisible = true;
    data.form = {};  // 清空表单
};

// 保存（新增/编辑）
const save = () => {
    formRef.value.validate(valid => {
        if (!valid) return;  // 校验失败
        data.form.id ? update() : add();  // 根据是否有id判断是新增还是编辑
    });
};

// 新增预订（调用后端 /booking/add 接口）
const add = () => {
    request.post('/booking/add', data.form).then(res => {
        if (res.code === '200') {
            data.formVisible = false;
            ElMessage.success('新增预订成功');
            load();  // 刷新数据
        } else {
            ElMessage.error(res.msg);
        }
    });
};

// 打开编辑对话框（深拷贝避免影响原数据）
const handleUpdate = (row) => {
    data.form = JSON.parse(JSON.stringify(row));
    data.formVisible = true;
};

// 编辑预订（调用后端 /booking/update 接口）
const update = () => {
    request.put('/booking/update', data.form).then(res => {
        if (res.code === '200') {
            data.formVisible = false;
            ElMessage.success('更新预订成功');
            load();  // 刷新数据
        } else {
            ElMessage.error(res.msg);
        }
    });
};

// 单条删除（调用后端 /booking/deleteById/{id} 接口）
const del = (id) => {
    ElMessageBox.confirm('删除后无法恢复，确认删除？', '提示', { type: 'warning' })
        .then(() => {
            request.delete(`/booking/deleteById/${id}`).then(res => {
                if (res.code === '200') {
                    ElMessage.success('删除成功');
                    load();  // 刷新数据
                } else {
                    ElMessage.error(res.msg);
                }
            });
        });
};

// 批量删除（调用后端 /booking/deleteBatch 接口）
const delBatch = () => {
    if (data.ids.length === 0) {
        ElMessage.warning('请选择要删除的预订');
        return;
    }
    ElMessageBox.confirm('删除后无法恢复，确认删除？', '提示', { type: 'warning' })
        .then(() => {
            request.delete('/booking/deleteBatch', { data: data.ids }).then(res => {
                if (res.code === '200') {
                    ElMessage.success('批量删除成功');
                    load();  // 刷新数据
                } else {
                    ElMessage.error(res.msg);
                }
            });
        });
};

// 处理表格选中项（记录选中的ID）
const handleSelectionChange = (rows) => {
    data.ids = rows.map(row => row.id);
};

// 初始化
onMounted(() => {
  load();  // 初始加载
  startAutoRefresh();
});

// 组件销毁时清除定时器
onUnmounted(() => {
  stopAutoRefresh();
});
</script>

<style scoped>
/* 可选样式调整（与现有组件保持一致） */
.el-table .el-table__cell {
    padding: 8px 0;
}
</style>